﻿using Newtonsoft.Json.Linq;
using Qimen.Api;
using Qimen.Api.Request;
using QimenCloud.Api;
using QimenCloud.Api.sceneqimen.Request;
using QimenCloud.Api.sceneqimen.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Top.Api;
using TrinityAPI.Base;
using TrinityAPI.Base.Models;
using TrinityAPI.Base.Tools;

namespace Taobao.Open.Platform
{
    public class QimenGateway : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var request = args.Length > 0 ? args[0] as JObject : dataset.GetJsonObject("request");
            string extendProps = request.GetJsonObject("extendProps").ToString();

            var constant = dataset.GetJsonObject("constant");
            var taobaoQimenAPIConfig = constant.GetNecessaryJsonObject("taobaoQimenERPAPIConfig", "constant");
            string url = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("url", "constant.taobaoQimenERPAPIConfig");
            string appkey = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("app_key", "constant.taobaoQimenERPAPIConfig");
            string appsecret = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("app_secret", "constant.taobaoQimenERPAPIConfig");
            string targetAppKey = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("targetAppKey", "constant.taobaoQimenERPAPIConfig");
            string disableLog = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("disableLog", "constant.taobaoQimenERPAPIConfig");

            try
            {
                if (url.ToLower().Contains("qimen"))
                {
                    string customerId = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("customerid", "constant.taobaoQimenERPAPIConfig");
                    string sessionKey = taobaoQimenAPIConfig.GetNecessaryJsonObjectStringValue("app_session", "constant.taobaoQimenERPAPIConfig");
                    //通过SDK调用奇门接口
                    DefaultQimenCloudClient client = new DefaultQimenCloudClient(url, appkey, appsecret);
                    TaobaoPosDeliveryorderGetRequest req = new TaobaoPosDeliveryorderGetRequest();
                    if (disableLog != null && disableLog.ToLower() == "true")
                    {
                        //禁用调试日志
                        client.SetDisableTrace(true);
                    }
                    req.Page = 1L;
                    req.PageSize = 20L;
                    req.OrderStatus = "NEW";
                    req.StartTime = "2021-10-26 18:00";
                    req.EndTime = "2021-10-26 19:00";
                    req.Customerid = customerId;
                    req.SetTargetAppKey(targetAppKey);
                    req.ExtendProps = extendProps;
                    TaobaoPosDeliveryorderGetResponse rsp = client.Execute(req, sessionKey);

                    var responseObject = JObject.Parse(rsp.Body).GetJsonObject("response");
                    if (responseObject == null)
                    {
                        responseObject = JObject.Parse(rsp.Body);
                    }

                    if (responseObject.GetJsonObjectStringValue("flag") != "success")
                    {
                        throw new Exception(responseObject.ToString());
                    }

                    return JObject.Parse(responseObject.GetJsonObjectStringValue("extendProps"));
                }
                else
                {
                    //奇门云网关，即自定义奇门接口
                    DefaultQimenCloudClient client = new DefaultQimenCloudClient(url, appkey, appsecret);
                    TrinityWmsExtendQueryRequest req = new TrinityWmsExtendQueryRequest();
                    if (disableLog != null && disableLog.ToLower() == "true")
                    {
                        //禁用调试日志
                        client.SetDisableTrace(true);
                    }
                    req.SetTargetAppKey(appkey);
                    req.ExtendProps = extendProps;
                    TrinityWmsExtendQueryResponse rsp = client.Execute(req);

                    var responseObject = JObject.Parse(rsp.Body).GetJsonObject("response");
                    if (responseObject == null)
                    {
                        responseObject = JObject.Parse(rsp.Body);
                    }

                    if (responseObject.GetJsonObjectStringValue("err_flag") != "success")
                    {
                        throw new Exception(responseObject.ToString());
                    }

                    return JObject.Parse(responseObject.GetJsonObjectStringValue("extendProps"));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Info("QimenGateway fail: " + ex.ToString());
                throw ex;
            }

        }
    }

    /// <summary>
    /// TOP API: trinity.wms.extend.query
    /// </summary>
    public class TrinityWmsExtendQueryRequest : BaseQimenCloudRequest<TrinityWmsExtendQueryResponse>
    {
        /// <summary>
        /// extendProps
        /// </summary>
        public string ExtendProps { get; set; }

        #region IQimenCloudRequest Members

        public override string GetApiName()
        {
            return "trinity.wms.extend.query";
        }

        public override IDictionary<string, string> GetParameters()
        {
            TopDictionary parameters = new TopDictionary();
            parameters.Add("extendProps", this.ExtendProps);
            if (this.otherParams != null)
            {
                parameters.AddAll(this.otherParams);
            }
            return parameters;
        }

        public override void Validate()
        {
        }

        #endregion
    }

    public class TrinityWmsExtendQueryResponse : QimenCloudResponse
    {
        /// <summary>
        /// extendProps
        /// </summary>
        [XmlElement("extendProps")]
        public string ExtendProps { get; set; }

    }
}
